package org.seeplnframework.skyeye.logback.api.listener;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.filter.Filter;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.seeplnframework.skyeye.common.constants.SysConstant;
import org.seeplnframework.skyeye.common.util.ConfigUtils;
import org.seeplnframework.skyeye.common.util.HashedWheelTask;
import org.seeplnframework.skyeye.common.util.SkyEyeStringValueResolverHelper;
import org.seeplnframework.skyeye.logback.api.filter.LogbackFilter;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * logback初始化
 */
@Slf4j
public class LogbackApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // 初始化配置属性
        ConfigUtils.initProperties(applicationContext);
        // 设置log filter，初始化动作
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
        Appender<ILoggingEvent> appender = ImmutableList
                .of("FILE", "file_business", "ASYNC_FILE")
                .parallelStream()
                .map(logger::getAppender)
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);

        if (appender != null) {
            List<Filter<ILoggingEvent>> filters = appender.getCopyOfAttachedFiltersList();
            for (Filter<ILoggingEvent> filter : filters) {
                if (filter instanceof LogbackFilter) {
                    return;
                }
            }
            appender.addFilter(new LogbackFilter());
            // 初始化任务调度器
            HashedWheelTask.init();
            // 项目启动后发送欢迎语
            //log.error(SysConstant.WELCOME);
        }
    }

}

